package com.hwadee.property.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hwadee.property.mapper.NoticeMapper;
import com.hwadee.property.pojo.*;
import com.hwadee.property.service.*;
import com.hwadee.property.util.DateUtil;
import com.hwadee.property.util.FileUtil;
import com.hwadee.property.dto.PageResult;
import com.hwadee.property.util.ErrorCodes;
import com.hwadee.property.util.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice> implements INoticeService {

    @Autowired
    private NoticeMapper noticeMapper;

    @Autowired
    private IUserService userService;

    @Autowired
    private ICommunityService communityService;

    @Autowired
    private IBuildingService buildingService;

    @Autowired
    private IHouseService houseService;

    @Autowired
    private FileUtil fileUtil;

    @Override
    public PageResult<Notice> getPage(int current, int size, Long communityId, String title) {
        // 校验参数
        if (current <= 0 || size <= 0) {
            throw new BusinessException(ErrorCodes.INVALID_PARAMETER, "分页参数无效");
        }

        // 计算 offset
        int offset = (current - 1) * size;

        // 获取CommunityID对应的PropertyID
        if (communityId!=null) {
            List<User> propertyList = new ArrayList<>();
            propertyList = userService.listPropertiesByCommunityId(communityId);

            // 查询总记录数
            int total = 0;
            for (User i : propertyList){
                total += noticeMapper.countNotices(i.getId(), title);
            }

            // 只有当 total > 0 时才查询数据
            List<Notice> records = new ArrayList<>();
            if (total > 0 ){
                for (User i : propertyList){
                    records.addAll(noticeMapper.getNotices(i.getId(), title, size, offset));
                }
            }

            // 返回分页结果
            return new PageResult<>(total, current, size, records);
        }else {
            int total = noticeMapper.countAllNotices(title);

            List<Notice> records = new ArrayList<>();
            if (total > 0 ){
                records = noticeMapper.getAllNotices(title, size, offset);
            }

            return new PageResult<>(total, current, size, records);
        }
    }


    @Override
    public List<Notice> listByPropertyStaffId(Long propertyStaffId) {
        // 校验参数
        if (propertyStaffId == null || propertyStaffId <= 0) {
            throw new BusinessException(ErrorCodes.INVALID_PARAMETER, "无效的物业人员ID");
        }

        // 使用 MyBatis-Plus 的 QueryWrapper 构建查询条件
        QueryWrapper<Notice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("property_staff_id", propertyStaffId);
        return this.list(queryWrapper);
    }

    @Override
    public boolean publishNotice(Notice notice) {
        // 校验参数
        if (notice == null) {
            throw new BusinessException(ErrorCodes.INVALID_PARAMETER, "公告内容不能为空");
        }

        // 设置发布时间
        notice.setPublishDate(DateUtil.dateToString(new Date()));
        notice.setUpdateDate(DateUtil.dateToString(new Date()));
        return this.save(notice);
    }

    @Override
    public boolean updateNotice(Long noticeID, String title, String content, String remark, MultipartFile attachment) {
        // 校验参数
        if (noticeID == null || noticeID <= 0) {
            throw new BusinessException(ErrorCodes.INVALID_PARAMETER, "无效的公告ID");
        }

        // 校验公告是否存在
        Notice notice = this.getById(noticeID);
        if (notice == null) {
            throw new BusinessException(ErrorCodes.NOT_FOUND, "公告信息不存在");
        }

        // 设置更新时间
        if (title != null) notice.setTitle(title);
        if (content != null) notice.setContent(content);
        if (remark != null) notice.setRemark(remark);
        if (attachment != null) {
            String attachmentPath = fileUtil.checkIfExist(notice.getAttachment(), "notice");
            if (attachmentPath != null) {
                fileUtil.deleteOldFile(attachmentPath, "notice");
            }
            attachmentPath = fileUtil.uploadFileAndGetPath(attachment, "notice");
            notice.setAttachment(attachmentPath);
        }
        notice.setUpdateDate(DateUtil.dateToString(new Date()));

        return this.updateById(notice);
    }

    @Override
    public boolean deleteNotice(Long id) {
        // 校验参数
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCodes.INVALID_PARAMETER, "无效的公告ID");
        }

        // 校验公告是否存在
        Notice notice = this.getById(id);
        if (notice == null) {
            throw new BusinessException(ErrorCodes.NOT_FOUND, "公告信息不存在");
        }

        String attachment = notice.getAttachment();
        if (attachment != null) {
            String attachmentPath = fileUtil.checkIfExist(attachment, "notice");
            if (attachmentPath != null) {
                fileUtil.deleteOldFile(attachmentPath, "notice");
            }
        }

        return this.removeById(id);
    }

    @Override
    public PageResult<Notice> listByOwnerId(int current, int size, String title, Long userId) {
        if (userId == null) {
            throw new BusinessException(ErrorCodes.INVALID_PARAMETER, "业主ID不能为空");
        }

        // 获取用户房屋 -> 楼栋 -> 小区
        List<House> houseList = houseService.listByOwnerId(userId);
        Set<Long> communityIds = houseList.stream()
                .map(h -> buildingService.getById(h.getBuildingId()))
                .filter(Objects::nonNull)
                .map(b -> communityService.getById(b.getCommunityId()))
                .filter(Objects::nonNull)
                .map(Community::getId)
                .collect(Collectors.toSet());

        if (communityIds.isEmpty()) {
            return PageResult.of(0, current, size, Collections.emptyList());
        }

        // 获取所有物业人员
        Set<Long> staffIds = new HashSet<>();
        for (Long communityId : communityIds) {
            List<User> users = userService.listPropertiesByCommunityId(communityId);
            users.forEach(u -> staffIds.add(u.getId()));
        }

        if (staffIds.isEmpty()) {
            return PageResult.of(0, current, size, Collections.emptyList());
        }

        // 调用Mapper统一查询
        int total = noticeMapper.countNoticesByStaffIds(new ArrayList<>(staffIds), title);
        List<Notice> records = Collections.emptyList();
        if (total > 0) {
            int offset = (current - 1) * size;
            records = noticeMapper.getNoticesByStaffIds(new ArrayList<>(staffIds), title, size, offset);
        }

        return PageResult.of(total, current, size, records);
    }


    @Override
    public List<Notice> listByCommunityId(Long communityId) {
        // 校验小区ID
        if (communityId == null) {
            throw new BusinessException(ErrorCodes.INVALID_PARAMETER, "小区ID不能为空");
        }
        List<Notice> noticeList = new ArrayList<>();
        List<User> propertyList = userService.listPropertiesByCommunityId(communityId);
        for (User i: propertyList){
            noticeList.addAll(listByPropertyStaffId(i.getId()));
        }
        return noticeList;
    }
}
